<!--
 * @Description: 个人资料页面 - 提供用户个人信息管理、密码修改、安全设置和登录记录功能
 * @Author: lujq
 * @Date: 2025-01-13
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-13 14:30:00
-->
<template>
  <div class="profile">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">个人信息</span>
            </div>
          </template>
          
          <div class="profile-info">
            <div class="avatar-section">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><User /></el-icon>
              </el-upload>
              <div class="upload-tip">点击上传头像</div>
            </div>
            
            <div class="info-item">
              <label>用户名：</label>
              <span>{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <label>姓名：</label>
              <span>{{ userInfo.realName }}</span>
            </div>
            <div class="info-item">
              <label>邮箱：</label>
              <span>{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <label>手机：</label>
              <span>{{ userInfo.phone }}</span>
            </div>
            <div class="info-item">
              <label>部门：</label>
              <span>{{ userInfo.department }}</span>
            </div>
            <div class="info-item">
              <label>职位：</label>
              <span>{{ userInfo.position }}</span>
            </div>
            <div class="info-item">
              <label>注册时间：</label>
              <span>{{ formatDate(userInfo.createTime) }}</span>
            </div>
            <div class="info-item">
              <label>最后登录：</label>
              <span>{{ formatDate(userInfo.lastLoginTime) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧设置区域 -->
      <el-col :span="16">
        <el-card class="settings-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">账户设置</span>
            </div>
          </template>
          
          <el-tabs v-model="activeTab" class="profile-tabs">
            <!-- 基本信息编辑 -->
            <el-tab-pane label="基本信息" name="basic">
              <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
                </el-form-item>
                <el-form-item label="邮箱地址" prop="email">
                  <el-input v-model="editForm.email" placeholder="请输入邮箱地址" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
                </el-form-item>
                <el-form-item label="部门">
                  <el-select v-model="editForm.department" placeholder="请选择部门">
                    <el-option label="销售部" value="sales" />
                    <el-option label="市场部" value="marketing" />
                    <el-option label="技术部" value="technology" />
                    <el-option label="财务部" value="finance" />
                    <el-option label="人事部" value="hr" />
                  </el-select>
                </el-form-item>
                <el-form-item label="职位">
                  <el-input v-model="editForm.position" placeholder="请输入职位" />
                </el-form-item>
                <el-form-item label="个人简介">
                  <el-input
                    v-model="editForm.bio"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入个人简介"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateBasicInfo">保存修改</el-button>
                  <el-button @click="resetBasicForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <!-- 密码修改 -->
            <el-tab-pane label="修改密码" name="password">
              <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
                <el-form-item label="当前密码" prop="currentPassword">
                  <el-input
                    v-model="passwordForm.currentPassword"
                    type="password"
                    placeholder="请输入当前密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    v-model="passwordForm.newPassword"
                    type="password"
                    placeholder="请输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input
                    v-model="passwordForm.confirmPassword"
                    type="password"
                    placeholder="请再次输入新密码"
                    show-password
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updatePassword">修改密码</el-button>
                  <el-button @click="resetPasswordForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <!-- 安全设置 -->
            <el-tab-pane label="安全设置" name="security">
              <div class="security-settings">
                <div class="security-item">
                  <div class="security-info">
                    <h4>登录保护</h4>
                    <p>开启后，登录时需要验证手机验证码</p>
                  </div>
                  <el-switch v-model="securitySettings.loginProtection" />
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>操作验证</h4>
                    <p>重要操作时需要验证身份</p>
                  </div>
                  <el-switch v-model="securitySettings.operationVerification" />
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>自动登出</h4>
                    <p>长时间无操作自动退出登录</p>
                  </div>
                  <el-switch v-model="securitySettings.autoLogout" />
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <h4>登录通知</h4>
                    <p>有新设备登录时发送通知</p>
                  </div>
                  <el-switch v-model="securitySettings.loginNotification" />
                </div>
                
                <el-button type="primary" @click="saveSecuritySettings" style="margin-top: 20px;">
                  保存安全设置
                </el-button>
              </div>
            </el-tab-pane>
            
            <!-- 登录记录 -->
            <el-tab-pane label="登录记录" name="loginHistory">
              <el-table :data="loginHistory" style="width: 100%">
                <el-table-column prop="loginTime" label="登录时间" width="180">
                  <template #default="{ row }">
                    {{ formatDate(row.loginTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="ip" label="IP地址" width="150" />
                <el-table-column prop="location" label="登录地点" width="200" />
                <el-table-column prop="device" label="设备信息" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                      {{ row.status === 'success' ? '成功' : '失败' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination-wrapper">
                <el-pagination
                  v-model:current-page="loginHistoryPage.current"
                  v-model:page-size="loginHistoryPage.size"
                  :page-sizes="[10, 20, 50, 100]"
                  :total="loginHistoryPage.total"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleLoginHistorySizeChange"
                  @current-change="handleLoginHistoryCurrentChange"
                />
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User } from '@element-plus/icons-vue'

// 响应式数据
const activeTab = ref('basic')
const editFormRef = ref()
const passwordFormRef = ref()

// 用户信息
const userInfo = reactive({
  username: 'admin',
  realName: '系统管理员',
  email: 'admin@fabric-sales.com',
  phone: '13800138000',
  department: '技术部',
  position: '系统管理员',
  avatar: '',
  bio: '负责系统维护和技术支持工作',
  createTime: '2024-01-01T00:00:00.000Z',
  lastLoginTime: '2024-12-23T10:30:00.000Z'
})

// 编辑表单
const editForm = reactive({
  realName: '',
  email: '',
  phone: '',
  department: '',
  position: '',
  bio: ''
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 安全设置
const securitySettings = reactive({
  loginProtection: true,
  operationVerification: false,
  autoLogout: true,
  loginNotification: true
})

// 登录记录
const loginHistory = ref([
  {
    loginTime: '2024-12-23T10:30:00.000Z',
    ip: '192.168.1.100',
    location: '上海市浦东新区',
    device: 'Chrome 120.0 / Windows 10',
    status: 'success'
  },
  {
    loginTime: '2024-12-22T14:20:00.000Z',
    ip: '192.168.1.100',
    location: '上海市浦东新区',
    device: 'Chrome 120.0 / Windows 10',
    status: 'success'
  },
  {
    loginTime: '2024-12-21T09:15:00.000Z',
    ip: '192.168.1.100',
    location: '上海市浦东新区',
    device: 'Chrome 120.0 / Windows 10',
    status: 'success'
  }
])

const loginHistoryPage = reactive({
  current: 1,
  size: 10,
  total: 3
})

// 表单验证规则
const rules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  
  if (isJPG && isLt2M) {
    // 模拟上传成功
    const reader = new FileReader()
    reader.onload = (e) => {
      if (e.target && typeof e.target.result === 'string') {
        userInfo.avatar = e.target.result
      }
    }
    reader.readAsDataURL(file)
  }
  
  return false // 阻止自动上传
}

const updateBasicInfo = async () => {
  try {
    await editFormRef.value.validate()
    
    // 更新用户信息
    Object.assign(userInfo, editForm)
    
    ElMessage.success('基本信息更新成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const resetBasicForm = () => {
  Object.assign(editForm, {
    realName: userInfo.realName,
    email: userInfo.email,
    phone: userInfo.phone,
    department: userInfo.department,
    position: userInfo.position,
    bio: userInfo.bio
  })
}

const updatePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    // 这里应该调用API修改密码
    ElMessage.success('密码修改成功')
    resetPasswordForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
  passwordFormRef.value?.clearValidate()
}

const saveSecuritySettings = () => {
  ElMessage.success('安全设置保存成功')
}

const handleLoginHistorySizeChange = (size: number) => {
  loginHistoryPage.size = size
  // 重新加载数据
}

const handleLoginHistoryCurrentChange = (current: number) => {
  loginHistoryPage.current = current
  // 重新加载数据
}

// 初始化
onMounted(() => {
  resetBasicForm()
})
</script>

<style scoped>
.profile {
  padding: 20px;
}

.profile-card,
.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 30px;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: block;
  object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409eff;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-item span {
  color: #303133;
  text-align: right;
  flex: 1;
}

.profile-tabs {
  margin-top: 20px;
}

.security-settings {
  padding: 20px 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-info h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #303133;
}

.security-info p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.form-text {
  margin-left: 10px;
  color: #909399;
}
</style>